package demo1;

import java.util.Arrays;
import java.util.Comparator;

class StudentSort implements Comparable<StudentSort>{
    public String name;
    public int age;

    public StudentSort(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(StudentSort o) {
        if(this.age - o.age > 0) {
            return 1;
        }else if(this.age - o.age < 0) {
            return -1;
        }else {
            return 0;
        }
        //return 0;
    }
}
//todo: Comparator接口当中 不止一个抽象方法  那么  为什么只需要实现一个compare方法就好了
class AgeComparator implements Comparator<StudentSort> {

    @Override
    public int compare(StudentSort o1, StudentSort o2) {
        return o1.age - o2.age;
    }
}

class NameComparator implements Comparator<StudentSort> {

    @Override
    public int compare(StudentSort o1, StudentSort o2) {
        return o1.name.compareTo(o2.name);
    }
}

public class TestSort {


    public static void main(String[] args) {
       StudentSort[] students = new StudentSort[3];
        students[0] = new StudentSort("zhangsan", 10);
        students[1] = new StudentSort("lisi", 40);
        students[2] = new StudentSort("wangwu", 5);

        AgeComparator ageComparator = new AgeComparator();//按照年龄排序
        Arrays.sort(students, ageComparator);
        System.out.println(Arrays.toString(students));

        NameComparator nameComparator = new NameComparator();//按照姓名排序
        Arrays.sort(students, nameComparator);
        System.out.println(Arrays.toString(students));
    }
}

